/*

Copyright (c) by Emil Valkov,
All rights reserved.

License: http://www.opensource.org/licenses/bsd-license.php

*/

#include <opencv/cv.h>
#include <opencv2/opencv.hpp>

#include "RaspiCamCV.h"

#include <stdio.h>
#include <ctime>
#include <iostream>
#include <unistd.h>
#include <sys/time.h>

using namespace std;
using namespace cv;


int main(int argc, const char** argv){
	RaspiCamCvCapture * capture = raspiCamCvCreateCameraCapture(0); // Index doesn't really matter
	if (isRaspiCamError(capture)){
		cerr << RaspiCamErrorMessage(capture);
		return 0;
	}
	cvNamedWindow("RaspiCamTest", 1);
	Mat image; 
	//IplImage * temp;
	timeval a;
	timeval b;

	uchar * ptr = NULL;
	uchar * out = new uchar[8];

	gettimeofday(&a,0);
	bool condition = true;
	double average[3] = {0.0, 0.0, 0.0};
	while(condition && !isRaspiCamError(capture)){
		image = Mat(raspiCamCvQueryFrame(capture));
		//printf("Width %d, height %d\n",image->width,image->height);
		imshow("RaspiCamTest",image);
		// cvReleaseImage(&image);
		cvWaitKey(0);
		ptr = image.ptr(0);
		cout << "Row Col Chan: " << image.rows <<' '<< image.cols << ' ' << image.channels()<< endl;

		for (int i = 0; i < image.rows; i++){
			for (int j = 0; j < image.cols; j++){
				average[0] += image.at<Vec3b>(i,j)[0];
				average[1] += image.at<Vec3b>(i,j)[1];
				average[2] += image.at<Vec3b>(i,j)[2];
			}
		}		
		cout << "Avg Red:   " 	<< average[0]/(image.rows * image.cols) << endl;
		cout << "Avg Green: " 	<< average[1]/(image.rows * image.cols) << endl;
		cout << "Avg Blue:  " 	<< average[2]/(image.rows * image.cols) << endl;
		

		condition = false;
		  
		  
	}
	if (isRaspiCamError(capture)){
		cout << RaspiCamErrorMessage(capture);
	}
	gettimeofday(&b,0);

	cout << "diff: " << (b.tv_sec - a.tv_sec) << endl;



	destroyWindow("RaspiCamTest");
	//cvReleaseImage(&image);
	raspiCamCvReleaseCapture(&capture);
	return 0;
}
